[Ruby] How can I randomly iterate through a large Range?

Posted by void on Stack Overflow See other posts from Stack Overflow or by void
Published on 2010-03-17T04:30:43Z Indexed on 2010/03/17 4:41 UTC
Read the original article Hit count: 221

Filed under:
|
|
|

I would like to randomly iterate through a range. Each value will be visited only once and all values will eventually be visited. For example:

(0..9).sort_by{rand}.map{|x| f(x)}

where f(x) is some function that operates on each value. A Fisher-Yates shuffle could be used to increase efficiency, but this code is sufficient for many purposes.

My problem is that sort_by will transform the range into an array, which is not cool because I am working with astronomically large numbers. Ruby will quickly consume a large amount of RAM trying to create a monstrous array. This is also why the following code will not work:

tried = {} # store previous attempts
bigint = 99**99
bigint.times {
    x = rand(bigint)
    redo if tried[x]
    tried[x] = true
    f(x) # some function
}

This code is very naive and quickly runs out of memory as tried obtains more entries.

What sort of algorithm can accomplish what I am trying to do?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about random